/* 离线工单数据处理*/
import dayjs from 'dayjs';
import {
	postSyncData, backupSyncData
} from '@/apis/workOrder.js';
import { uploadFile } from '@/apis/system.js';
import sidaAI from '@/utils/ai';
// #ifdef MP-WEIXIN 
// 微信小程序存储优化 - json文件存储（h5环境保留原有方案）
// 微信小程序单个 key 允许存储的最大数据长度为 1MB，所有数据存储上限为 10MB
import { setFile, getFile, removeFile, clearAllFiles } from '@/utils/wxFileStorage.js';
// #endif
import { MODEL_ID_MAP } from '@/utils/constants.js';
import { getPathInfo, setWatermarkJson } from '@/utils/watermarkTool.js';
import {  getPlanDetail, getLoaclTypes, getAllWorkItems } from '@/apis/workOrder.js';
const apps = getApp();

const statusNames = {
	1: '待开始',
	2: '开始任务',
	3: '提交任务',
	5: '维保签字',
	4: '完成任务'
};
// 获取离线工单详情
export function getLocalPlan(planId) {
	return new Promise((resoleve) => {
		// #ifdef H5 
		uni.getStorage({
			key: 'local' + planId,
			success: (res) => {
				resoleve(res.data);
			},
			fail: () => {
				resoleve({});
			}
		});
		// #endif
		// #ifdef MP-WEIXIN 
		getFile({
			key: 'local' + planId,
			success: (res) => {
				resoleve(res.data);
			},
			fail: () => {
				resoleve({});
			}
		});
		// #endif
	});
}

// 同步更新离线工作项数据（在线编辑某个工作项后
export function setOfflineWorkerItem(planId, item) {
	// console.log('同步更新离线工作项数据（在线编辑某个工作项后');
	// 更新详情数据

	// #ifdef H5 
	uni.getStorage({
		key: 'local' + planId,
		success: (res) => {
			let info = res.data;

			for (let i = 0; i < info.orgTemplate.length; i++) {
				if (info.orgTemplate[i].checkHistoryId && item.checkHistoryId == info.orgTemplate[i].checkHistoryId) {
					info.orgTemplate[i] = item;
					break;
				}
			}

			uni.setStorage({
				key: 'local' + planId,
				data: info
			});
		}
	});
	// #endif

	// #ifdef MP-WEIXIN 
	getFile({
		key: 'local' + planId,
		success: (res) => {
			let info = res.data;

			for (let i = 0; i < info.orgTemplate.length; i++) {
				if (info.orgTemplate[i].checkHistoryId && item.checkHistoryId == info.orgTemplate[i].checkHistoryId) {
					info.orgTemplate[i] = item;
					break;
				}
			}

			setFile({
				key: 'local' + planId,
				data: info
			});
		}
	});
	// #endif
}

// 调整离线缓存任务状态
export function setListStatus({ planId, status, detail }) {
	console.log('整离线缓存任务状态', planId, status);
	const statusList = {
		1: '待开始',
		2: '进行中',
		3: '已提交',
		5: '已提交',
		4: '已完成'
	};

	uni.getStorage({
		key: 'offline_orders',
		success: (res) => {
			let list = res.data;
			const disFinishList = list.records || [];
			let off = false;
			for (let i = 0; i < disFinishList.length; i++) {
				if (off) {
					break;
				}
				for (let j = 0; j < disFinishList[i].maintainPlanContentListVos.length; j++) {
					const recordsx = disFinishList[i].maintainPlanContentListVos[j].list;
					if (off) {
						break;
					}
					// console.log('records',recordsx)
					for (let k = 0; k < recordsx.length; k++) {
						const item = recordsx[k];
						if (item.planId == planId) {
							item.status = status;
							item.statusName = statusList[status];
							off = true;
							break;
						}
					}
				}
			}

			uni.setStorage({
				key: 'offline_orders',
				data: list
			});
		}
	});

	// 更新详情数据
	if (!detail || !detail.planId) {
		return;
	}
	let info = detail;
	info.status = status;
	info.statusName = statusList[status];
	// #ifdef H5 
	uni.setStorage({
		key: 'local' + planId,
		data: info
	});
	// #endif
	// #ifdef MP-WEIXIN 
	setFile({
		key: 'local' + planId,
		data: info
	});
	// #endif
}

// 缓存工单详情离线数据
export function setLocalPlan(planId, detail) {
	return new Promise((resolve) => {
		// if (detail.orgTemplate && detail.orgTemplate.length > 50) {
		// 	resolve({});
		// 	return;
		// }
		let setStorage = uni.setStorage;
		// #ifdef MP-WEIXIN 
		setStorage = setFile;
		// #endif
		setStorage({
			key: 'local' + planId,
			data: detail,
			success: () => {
				// 记录保存的所有id 方便后面清除 防止爆缓存
				let localPlanIds = (uni.getStorageSync('localPlanIds') || '').split(',');
				if (localPlanIds.length && localPlanIds[0] == '') {
					localPlanIds.splice(0, 1);
				}
				if (localPlanIds.indexOf(planId) == -1) {
					localPlanIds.push(planId);
					uni.setStorageSync('localPlanIds', localPlanIds.join(','));
				}
				resolve(detail);
			},
			fail: () => {
				resolve({});
			}
		});
	});
}

// 设置待同步数据的工单id
export function setWorkingPlans(planId) {
	if (!planId) {
		return;
	}
	const workingPlans = uni.getStorageSync('workingPlans');
	let plans = workingPlans ? workingPlans.split(',') : [];
	if (plans.indexOf(planId) == -1) {
		plans.push(planId);
		uni.setStorageSync('workingPlans', plans.join(','));
	}
}
function setWorkItemMap({ elevatorId, planId, list = [], loaclIds = [], loaclNames = [] }) {
	let workItems = [];
	for (let i = 0; i < list.length; i++) {
		let item = {
			...list[i],
			elevatorId: elevatorId,
			planId: planId,
			updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
			// list[i].updateTime || dayjs().format("YYYY-MM-DD HH:mm:ss")
		};

		workItems.push(item);
	}
	return workItems;
}

// 备份数据
function setBackupsData(data, remove = false) {
	if (!data || !data.planId) {
		return;
	}
	if (remove) {
		let removeStorage = uni.removeStorage;
		// #ifdef MP-WEIXIN 
		removeStorage = removeFile;
		// #endif
		removeStorage({
			key: 'backupsData' + data.planId,
		});
		return;
	}
	let setStorage = uni.setStorage;
	// #ifdef MP-WEIXIN 
	setStorage = setFile;
	// #endif
	setStorage({
		key: 'backupsData' + data.planId,
		data: data,
		success: () => {
		},
		fail: () => {
		}
	});
}

// 删除图片缓存防止爆内存
function removeImgLocalInfo() {
	try {
		uni.getStorageInfo({
			success(res) {
				const isPureNumber = (str) => /^\d+$/.test(str);
				let keys = res.keys || [];
				for (let i = 0; i < keys.length; i++) {
					if (keys[i].length > 10 && isPureNumber(keys[i])) {
						uni.removeStorage({
							key: keys[i]
						});
					}
				}
				uni.setStorage({
					key: 'imgPaths',
					data: {}
				});
			}
		});
	} catch (error) {
		console.log(error);
	}
}

// 写入待同步数据
// type 
// signList 签到记录
// userId,planId,signImage,signDesc,signStatus,signTime,signOutImage,signOutDesc,signOutStatus,signOutTime
// checkHistories 工作项更变记录 内有checkRecords放添加记录详情列表
// logList 任务追踪日志记录
// signtures 签字记录
// 
export async function setSyncData(type, data) {
	if (!data.planId) {
		return;
	}
	const saveFuc = (planId, records) => {
		return new Promise((resoleve) => {
			let setStorage = uni.setStorage;
			// #ifdef MP-WEIXIN 
			setStorage = setFile;
			// #endif
			setStorage({
				key: 'syncData' + planId,
				data: records,
				success: (res) => {
					setWorkingPlans(planId);
					resoleve(res.data);
				},
				fail: () => {
					resoleve({});
				}
			});
		});
	};

	const findItem = (list) => {
		for (let i = 0; i < list.length; i++) {
			if (list[i].templateContentId == data.templateContentId) {
				// 找到工作项并往工作项操作记录中添加最新记录
				if (list[i].userRecordVOS) {
					let userRecordVOS = list[i].userRecordVOS;
					for (let k = 0; k < userRecordVOS.length; k++) {
						if (userRecordVOS[k].userId == data.userId) {
							userRecordVOS[k].recordVOList.unshift(data);
							break;
						}
						if (k == userRecordVOS.length - 1 && userRecordVOS[k].userId != data.userId) {
							userRecordVOS.unshift({
								recordVOList: [data],
								userId: data.userId,
								userName: data.userName
							});
							break;
						}
					}
					if (userRecordVOS.length == 0) {
						userRecordVOS.unshift({
							recordVOList: [data],
							userId: data.userId,
							userName: data.userName
						});
						break;
					}
				} else {
					list[i].userRecordVOS = [
						{
							recordVOList: [data],
							userId: data.userId,
							userName: data.userName
						}
					];
				}
				return;
			}
		}
	};

	let detail = await getLocalPlan(data.planId);
	if (!detail.planId) {
		uni.hideLoading();
		uni.showModal({
			title: '提示',
			content: '未找到离线工单数据，请使用在线作业',
			showCancel: false
		});
		return;
	}
	const nowDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
	let orgTemplate = JSON.parse(JSON.stringify(detail.orgTemplate));

	let workItems = setWorkItemMap({ elevatorId: detail.elevatorId, planId: data.planId, list: orgTemplate });// 遍历初始化每个工作项

	let local = {
		planId: data.planId,
		status: 2,
		planBeginTime: '',
		planEndTime: '',
		planCommitTime: '',
		maintainSignatureTime: '',
		signList: [],
		checkHistories: workItems,
		logList: [],
		signtures: [],
		finishDate: ''
	};
	let syncData = await getSyncData(data.planId);
	if (!syncData.planId) {
		syncData = local;
	}
	if (!syncData.finishDate) {
		if (detail.finishDate) {
			syncData.finishDate = `${detail.finishDate}${detail.finishDate && detail.finishDate.length < 18 ? ':00' : ''}`;
		} else {
			let date = dayjs().format('YYYY-MM-DD');
			let hour = Number(dayjs().format('HH')) + 2;
			let min = dayjs().format('mm');
			syncData.finishDate = `${date} ${hour}:${min}`;
		}
	}
	switch (type) {
	case 'signList':// 签到签退记录
		let record = {
			userId: data.userId,
			planId: data.planId,
			signImage: '',
			signDesc: '',
			signStatus: '',
			signTime: '',
			signOutImage: '',
			signOutDesc: '',
			signOutStatus: '',
			signOutTime: ''
		};
		if (data.signType == 1) {
			let isAdded = false;
			// 签到
			for (let i = 0; i < syncData.signList.length; i++) {
				if (syncData.signList[i].signTime == data.signTime) {
					isAdded = true;
					// 数据重复
					break;
				}
				if (!syncData.signList[i].signOutTime) {
					// 有未签退数据
					isAdded = true;
					break;
				}
			}

			if (isAdded) {
				// 数据重复 不上传
				return;
			}
			record.signImage = data.signImage;
			record.signTime = data.signTime;
			record.signStatus = data.signStatus;
			record.finishDate = `${data.finishDate}${data.finishDate && data.finishDate.length < 18 ? ':00' : ''}`;
			local.finishDate = `${data.finishDate}${data.finishDate && data.finishDate.length < 18 ? ':00' : ''}`;
			syncData.signList.push(record);

			for (let i = 0; i < detail.users.length; i++) {
				// 更新人员签到状态
				if (detail.users[i].userId == data.userId) {
					detail.users[i].userSignCount = (detail.users[i].userSignCount || 0) + 1;
					detail.users[i].signUser = { isPlanStatus: true };
					break;
				}
			}

			if (detail.status <= 1) {
				// 待开始 签到后改进行中
				detail.status = 2;
				// 修改本地列表状态
				setListStatus({ planId: detail.planId, status: 2, detail });
				local.planBeginTime = data.signTime;
			}
		} else {
			// 签退  看下有没有历史记录
			if (syncData.signList.length) {
				let signData = syncData.signList[syncData.signList.length - 1];
				signData.signOutImage = data.signImage;
				signData.signOutTime = data.signTime;
				signData.signOutStatus = data.signStatus;
			} else {
				record.signOutImage = data.signImage;
				record.signOutTime = data.signTime;
				record.signOutStatus = data.signStatus;
				syncData.signList.push(record);
			}

			for (let i = 0; i < detail.users.length; i++) {
				// 更新人员签到状态
				if (detail.users[i].userId == data.userId) {
					detail.users[i].signUser = { isPlanStatus: false };
					break;
				}
			}
		}

		await setLocalPlan(data.planId, detail);
		if (detail.status > 1) {
			// 已经开始过了工单  
		} else {
			syncData.status = 2;
			syncData.planBeginTime = data.signTime;
		}
		// 保存一份数据
		await saveFuc(data.planId, syncData);
		setSyncData('logList', {
			planId: data.planId,
			planStatus: syncData.status,
			typeName: data.signType == 1 ? '签到开始' : '签退',
			createTime: data.signTime,
			extBefore: {
				planUser: data.userId,
				// 离线 3
				signStatus: 3,
				image: data.signImage
			},
			createDate: data.signTime.split(' ')[0]
		});
		// 添加任务跟踪记录
		break;
	case 'checkHistories':
		// 工作项编辑
		// console.log('工作项编辑', data);
		for (let i = 0; i < syncData.checkHistories.length; i++) {
			if (syncData.checkHistories[i].templateContentId == data.templateContentId) {
				syncData.checkHistories[i] = data;
				break;
			}
		}

		// 找到原详情缓存，同步工作项数据
		for (let i = 0; i < detail.orgTemplate.length; i++) {
			if (detail.orgTemplate[i].templateContentId == data.templateContentId) {
				detail.orgTemplate[i] = data;
				break;
			}
		}

		// syncData.checkHistories.push(data);
		await saveFuc(detail.planId, syncData);
		setLocalPlan(detail.planId, detail);
		break;

	case 'logList':
		// 任务跟踪
		syncData.logList.push(data);

		await saveFuc(data.planId, syncData);
		// 保存一份数据
		break;

	case 'checkRecords':
		// 添加记录 
		data.createTime = nowDate;
		data.updateTime = nowDate;
		for (let i = 0; i < syncData.checkHistories.length; i++) {
			if (syncData.checkHistories[i].templateContentId == data.templateContentId) {
				if (syncData.checkHistories[i].waitRecords) {
					syncData.checkHistories[i].waitRecords.push(data);
					// 添加待同步记录
				} else {
					syncData.checkHistories[i].waitRecords = [data];
				}
				break;
			}
		}

		//  console.log('test', detail, data);
		// 找到原详情缓存，同步工作项数据
		findItem(detail.orgTemplate);
		// console.log('test', detail, data);

		// syncData.checkHistories.push(data);
		await saveFuc(detail.planId, syncData);
		await setLocalPlan(detail.planId, detail);
		break;

	case 'signtures':
		// 签字  signType 1维保 2物业

		syncData.signtures.push(data);
		if (data.signType == 1) {
			detail.status = 5;
			syncData.status = 5;
			syncData.maintainSignatureTime = nowDate;
			detail.signatureEstateStatus = {
				result: true
			};
		} else {
			syncData.planEndTime = nowDate;
			detail.status = 4;
			syncData.status = 4;
			delete data.userId;
		}

		if (detail.signRecords) {
			detail.signRecords.push(data);
		} else {
			detail.signRecords = [data];
		}

		await setLocalPlan(detail.planId, detail);
		await saveFuc(data.planId, syncData);
		// 保存一份数据
		setListStatus({ planId: detail.planId, status: detail.status, detail });
		break;
	case 'changeStatus':
		syncData.status = data.status;
		detail.status = data.status;
		const dateStr = dayjs().format('YYYY-MM-DD HH:mm:ss');
		if (data.status == 3) {
			syncData.planCommitTime = dateStr;
		}
		await saveFuc(detail.planId, syncData);
		// 保存一份数据
		await setLocalPlan(detail.planId, detail);

		setListStatus({ planId: detail.planId, status: data.status, detail });
		// 修改本地列表状态
		setSyncData('logList', {
			planId: detail.planId,
			planStatus: syncData.status,
			typeName: statusNames[syncData.status],
			createTime: dateStr,
			createDate: dateStr.split(' ')[0]
		});
		// 添加任务跟踪记录s

		break;

	default:
		break;
	}
}

// 获取待同步数据
export function getSyncData(planId) {
	return new Promise((resoleve) => {
		// #ifdef H5 
		uni.getStorage({
			key: 'syncData' + planId,
			success: (res) => {
				resoleve(res.data);
			},
			fail: () => {
				resoleve({});
			}
		});
		// #endif
		// #ifdef MP-WEIXIN 
		getFile({
			key: 'syncData' + planId,
			success: (res) => {
				resoleve(res.data);
			},
			fail: () => {
				resoleve({});
			}
		});
		// #endif
	});
}

// 缓存保养详情
export function preloadPlanDetails() {
	const offlineTime = uni.getStorageSync('offlineTime');
	let now = new Date().getTime();

	const waitplan = uni.getStorageSync('workingPlans');
	// 带同步工单
	if (offlineTime && now - offlineTime < 1 * 60 * 60 * 1000) {
		// 一小时内只缓存一次
		console.log('一小时内只缓存一次', offlineTime);
		return;
	} else {
		let localPlanIds = (uni.getStorageSync('localPlanIds') || '').split(',');
		let newLocalPlanIds = [];
		for (let i = 0; i < localPlanIds.length; i++) {
			if (!waitplan || waitplan.indexOf(localPlanIds[i]) == -1) {
				// 清一下旧缓存，防止垃圾缓存堆积
				uni.removeStorageSync('local' + localPlanIds[i]);
				removeFile('local' + localPlanIds[i]);
			} else {
				// 如果详情数据有修改待同步，不清缓存
				newLocalPlanIds.push(localPlanIds[i]);
			}
		}
		// uni.removeStorageSync('localPlanIds') 
		uni.setStorageSync('localPlanIds', newLocalPlanIds.join(','));
		// uni.removeStorageSync('offline_orders')   
	}
	const saveFucs = (item) => {
		const planId = item.planId;
		return new Promise(async (resolve) => {
			if (!waitplan || waitplan.indexOf(planId) == -1) {
				// console.log(planId)
				const res = await Promise.all([
					getPlanDetail({
						planId: planId
					}),
					getLoaclTypes({
						planId: planId
					}),
					getAllWorkItems({
						planId: planId
					})
				]);
				let planDetail = res[0].data;
				let locals = res[1].data.location || [];
				let templateTabs = res[1].data.template || [];
				let workerItems = res[2].data;

				let num = 0;
				for (let i = 0; i < locals.length; i++) {
					num = num + locals[i].workItemCount;
					locals[i].finished = 0;
				}
				locals.unshift({ tltName: '全部', workItemCount: num, finished: 0 });

				if (templateTabs.length > 1) {
					templateTabs.unshift({ name: '全部', id: '' });
				}

				let detail = { ...item, ...planDetail, elevatorId: item.elevatorId, planId: planId };
				detail.loacls = locals;
				detail.templateTabs = templateTabs;
				detail.orgTemplate = workerItems;
				detail.isStop = item.elevatorIsStop;
				setLocalPlan(planId, detail);
				// 缓存详情数据

				resolve();
			}
		});
	};

	uni.getStorage({
		key: 'offline_orders',
		success: async (res) => {
			console.log('offline_orders', 111, res);
			const local = res.data;
			const list = local.records || [];
			let orderNum = 10;
			for (let i = 0; i < list.length; i++) {
				for (let j = 0; j < list[i].maintainPlanContentListVos.length; j++) {
					const recordsx = list[i].maintainPlanContentListVos[j].list;
					for (let k = 0; k < recordsx.length; k++) {
						const item = recordsx[k];
						console.log('saveFucs', item);
						await saveFucs(item);
						orderNum--;
						console.log('orderNum', orderNum);
						if (orderNum <= 0) {
							break;
						}
					}
					if (orderNum <= 0) {
						break;
					}
				}
				if (orderNum <= 0) {
					break;
				}
			}
			uni.setStorageSync('offlineTime', new Date().getTime());
		}
	});
	return;
}

// 提交同步数据
export function submitData() {
	// return debounce(()=>{},400)
	const uploadLocalImgs = async (files) => {
		if (!files || files.length == 0) {
			return;
		}
		for (let k = 0; k < files.length; k++) {
			if (files[k].url && files[k].url.indexOf('aliyuncs.com') == -1) {
				let imgid = '';

				if (files[k].modelType) {
					// 需要跑模型
					const imgInfo = await getPathInfo(files[k].url);
					if (!imgInfo.model_result) {
						const result = await sidaAI.inferImageMultiModel(files[k].modelType,files[k].url);
						imgInfo.result = result.determine;
						imgInfo.model_result = JSON.stringify(result.results);
						imgInfo.model_id = MODEL_ID_MAP[files[k].modelType];
						imgInfo.type = 3;
						files[k].aiResult = result.determine;
						files[k].modelId = MODEL_ID_MAP[files[k].modelType];
						imgid = await setWatermarkJson(imgInfo);
					}
				}
				// 有本地图片，上传到服务器
				const imgres = await uploadFile(files[k].url, imgid);
				files[k].url = imgres.data.link;
				// console.log('img await1111111111111111111111111', files[k]);
			}
		}
		return;
	};
	return new Promise(async (resolve, reject) => {
		let plans = (uni.getStorageSync('workingPlans') || '').split(',');
		// console.log('syncData1', plans)
		let imgMap = {};
		// 图片预存map
		let errors = [];
		let errLogs = [];
		// 错误日志
		for (let i = 0; i < plans.length;) {
			const syncData = await getSyncData(plans[i]);
			try {
				if (syncData) {
					setBackupsData(syncData);
					if ((syncData.finishDate || '').split(':').length == 2) {
						syncData.finishDate = `${syncData.finishDate}${syncData.finishDate && syncData.finishDate.length < 18 ? ':00' : ''}`;
					}

					if (syncData.checkHistories) {
						// 工作项图片或视频校验一下同步服务端
						for (let j = 0; j < syncData.checkHistories.length;) {
							if (syncData.checkHistories[j].recordData.type >= 3) {
								if (syncData.checkHistories[j].recordData.val) {
									let files = syncData.checkHistories[j].recordData.val;
									await uploadLocalImgs(files);
								} else {
									syncData.checkHistories[j].recordData.val = [];
								}
							}

							if (syncData.checkHistories[j].waitRecords) {
								// 操作记录里面的图片视频也同步一下
								let waitRecords = syncData.checkHistories[j].waitRecords;
								for (let k = 0; k < waitRecords.length;) {
									if (waitRecords[k].recordDataValue.files) {
										await uploadLocalImgs(waitRecords[k].recordDataValue.files.val);
									}
									if (waitRecords[k].recordDataValue.filesAfter) {
										await uploadLocalImgs(waitRecords[k].recordDataValue.filesAfter.val);
									}
									if (waitRecords[k].recordDataValue.filesBefore) {
										await uploadLocalImgs(waitRecords[k].recordDataValue.filesBefore.val);
									}
									k++;
								}
								syncData.checkHistories[j].checkRecords = waitRecords;
							}

							j++;
						}
					}

					if (syncData.signtures && syncData.signtures.length) {
						// 同步签字图片
						for (let i = 0; i < syncData.signtures.length; i++) {
							if (syncData.signtures[i].signImg && syncData.signtures[i].signImg.indexOf('aliyuncs.com') == -1) {
								// 有本地图片，上传到服务器
								const imgres = await uploadFile(syncData.signtures[i].signImg);
								syncData.signtures[i].signImg = imgres.data.link;
							}
						}
					}

					if (syncData.signList && syncData.signList.length) {
						// 同步签到签退图片
						for (let i = 0; i < syncData.signList.length; i++) {
							if (syncData.signList[i].signImage && syncData.signList[i].signImage.indexOf('aliyuncs.com') == -1) {
								let link = '';
								if (imgMap[syncData.signList[i].signImage]) {
									link = imgMap[syncData.signList[i].signImage];
								} else {
									// 签到模型
									const modelType = 1;
									let imgid = '';
									// #ifndef H5
									const imgInfo = await getPathInfo(syncData.signList[i].signImage);
									const result = await sidaAI.inferImageMultiModel(
										modelType,  
										syncData.signList[i].signImage
									);

									imgInfo.result = result.determine;
									imgInfo.model_result = JSON.stringify(result.results);
									imgInfo.model_id = MODEL_ID_MAP[modelType];
									imgInfo.type == 1;
									imgid = await setWatermarkJson(imgInfo);
									// #endif

									// 有本地图片，上传到服务器
									// console.log('imgInfo', imgid, imgInfo);
									const imgres = await uploadFile(syncData.signList[i].signImage, imgid);
									link = imgres.data.link;
									imgMap[syncData.signList[i].signImage] = link;
								}

								syncData.signList[i].signImage = link;
							}

							if (syncData.signList[i].signOutImage && syncData.signList[i].signOutImage.indexOf('aliyuncs.com') == -1) {
								let link = '';
								if (imgMap[syncData.signList[i].signOutImage]) {
									link = imgMap[syncData.signList[i].signOutImage];
								} else {
									// 签退模型
									const modelType = 2;
									let imgid = '';
									// #ifndef H5
									const imgInfo = await getPathInfo(syncData.signList[i].signOutImage);
									const result = await sidaAI.inferImageMultiModel(modelType,syncData.signList[i].signOutImage);
									imgInfo.result = result.determine;
									imgInfo.model_result = JSON.stringify(result.results);
									imgInfo.model_id = MODEL_ID_MAP[modelType];
									imgInfo.type = 2;
									imgid = await setWatermarkJson(imgInfo);
									// #endif

									// console.log('imgInfo', imgid, imgInfo, syncData.signList[i].signOutImage);
									// 有本地图片，上传到服务器
									const imgres = await uploadFile(syncData.signList[i].signOutImage, imgid);
									link = imgres.data.link;
									imgMap[syncData.signList[i].signOutImage] = link;
								}

								syncData.signList[i].signOutImage = link;
							}
						}
					}

					if (syncData.logList && syncData.logList.length) {
						// 同步任务跟踪
						for (let i = 0; i < syncData.logList.length; i++) {
							if (syncData.logList[i].extBefore && syncData.logList[i].extBefore.image && syncData.logList[i].extBefore.image.indexOf('aliyuncs.com') == -1) {
								let link = '';
								if (imgMap[syncData.logList[i].extBefore.image]) {
									link = imgMap[syncData.logList[i].extBefore.image];
								} else {
									// 有本地图片，上传到服务器
									const imgres = await uploadFile(syncData.logList[i].extBefore.image);
									link = imgres.data.link;
									imgMap[syncData.logList[i].extBefore.image] = link;
								}

								syncData.logList[i].extBefore.image = link;
								syncData.logList[i].ext = JSON.stringify(syncData.logList[i].extBefore);
							}
						}
					}
					if (syncData.planId) {
						let updateStatus = true;
						let times = new Date().getTime();
						if (apps.globalData.lastSyncOrder.id) {
							if (apps.globalData.lastSyncOrder.id == syncData.planId) {
								if (times - apps.globalData.lastSyncOrder.time < 3000) {
									// 3秒内同一工单重复同步不提交
									updateStatus = false;
								}
							}
						}
						if (updateStatus) {
							apps.globalData.lastSyncOrder.id = syncData.planId;
							apps.globalData.lastSyncOrder.time = times;
							await postSyncData(syncData);
							backupSyncData(syncData);
						}

						uni.removeStorage({
							key: 'syncData' + syncData.planId
						});
						removeFile({
							key: 'syncData' + syncData.planId
						});

						// 同步成功删除备份数据
						setBackupsData(syncData, true);
						// 同步成功删除本地图片缓存
						removeImgLocalInfo();
					}
				}
				console.log('syncData', syncData);
			} catch (error) {
				console.log('offline-862', error);
				errors.push(plans[i]);
				// 记录没同步成功的
				errLogs.push(error);
				if (syncData.planId) {
					backupSyncData(syncData);
				}

				// reject(error) 
			}

			i++;
		}
		uni.setStorageSync('workingPlans', errors.join(','));

		if (errors.length) {
			reject(errLogs);
		} else {
			resolve(plans);
		}
	});
}
